<template>
  <div class="mobile-container">
<!-- 导航栏 -->
<van-nav-bar title="古建筑彩绘文物调查管理系统" fixed @click-right="goToUser">
  <!-- 左侧插槽：显示“首页” -->
  <template #left>
    <!-- <span class="nav-text" @click="goHome">首页</span> -->
    <van-icon name="wap-home" class="nav-text" @click="goHome" size="18"/>
  </template>

  <!-- 右侧用户图标 -->
  <template #right>
    <van-icon name="user" size="18" />
  </template>
</van-nav-bar>
    <!-- 面包屑导航 -->
  <div class="breadcrumb">
    <span class="breadcrumb-item" @click="goHome">首页</span>
    <span class="breadcrumb-separator">></span>
    <span class="breadcrumb-separator">文物主体管理</span>
    <!-- <span class="breadcrumb-separator">></span> -->
    <!-- <span class="breadcrumb-item">编辑文物主体>{{ currentCategory.name }}</span> -->
  </div>

    <!-- 搜索 + 新增按钮 -->
    <div class="search-upload-container">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索名称、简介、地址等"
        @search="handleSearch"
        @clear="handleSearch"
        shape="round"
        class="search-bar"
      />
        <!-- 纯图标：搜索 -->
  <van-icon
    name="search"
    size="20"
    class="search-icon"
    @click="handleSearch"
    style="margin-right: 20px;"
  />
      <van-button
        v-if="userInfo.role === 'admin'"
        type="primary"
        size="small"
        round
        @click="goToAdd"
        class="add-btn"
        icon="plus"
      >
        新增文物主体
      </van-button>
    </div>

    <!-- 可滚动内容区 -->
    <div class="scrollable-content">
      <!-- 加载状态 -->
      <div v-if="componentState === 'loading'" class="state-placeholder">
        <van-loading type="spinner" size="24" vertical>加载中...</van-loading>
      </div>

      <!-- 空状态 -->
      <div v-else-if="componentState === 'empty' || categories.length === 0" class="state-placeholder">
        <van-empty description="暂无文物主体数据" />
      </div>

      <!-- 错误状态 -->
      <div v-else-if="componentState === 'error'" class="state-placeholder">
        <van-empty description="加载失败" image="error">
          <template #bottom>
            <van-button type="danger" size="small" @click="reloadData">重试</van-button>
          </template>
        </van-empty>
      </div>

      <!-- 文物列表 -->
      <div v-else class="relic-list">
        <van-swipe-cell v-for="item in categories" :key="item.id">
          <!-- 卡片主体 -->
          <template #default>
            <div class="relic-card" @click="goToMainPage(item.id, item.name)">
              <!-- 图片 -->
              <div class="image-wrapper">
                <van-image
                  v-if="item.image_base64"
                  :src="item.image_base64"
                  width="100%"
                  height="160"
                  fit="cover"
                  @click.stop="previewImage(item.image_base64)"
                />
                <div v-else class="image-placeholder">暂无图片</div>
              </div>

              <!-- 内容 -->
              <div class="content-wrapper">
                <h3 class="relic-name">{{ item.name }}</h3>

                <div class="info-grid">
                  <!-- 简介（可折叠） -->
                  <div class="info-item description-item">
                    <span class="label">简介：</span>
                    <div class="value-wrapper">
                      <p class="description-text" :class="{ expanded: expandedStates[item.id] }">
                        {{ item.description || '无描述' }}
                      </p>

                      <van-button
                        v-if="item.description && item.description.length > 50"
                        size="small"
                        type="primary"
                        plain
                        hairline
                        @click.stop="toggleExpand(item.id)"
                        class="expand-btn"
                      >
                        {{ expandedStates[item.id] ? '收起' : '展开' }}
                      </van-button>
                    </div>
                  </div>

                  <div class="info-item">
                    <span class="label">建筑年代：</span>
                    <span class="value">{{ item.construction_age || '未填写' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">建筑类型：</span>
                    <span class="value">{{ item.construction_type || '未填写' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">布局方位：</span>
                    <span class="value">{{ item.layout_orientation || '未填写' }}</span>
                  </div>

                  <!-- 保护等级（带详情弹窗） -->
                  <div class="info-item">
                    <span class="label">保护等级：</span>

                    <template v-if="parseProtectionLevel(item.protection_level).level">
                      <van-tag :type="getTagType(parseProtectionLevel(item.protection_level).level)" size="small">
                        {{ parseProtectionLevel(item.protection_level).level }}
                      </van-tag>
                    </template>
                    <span v-else>未评级</span>

                    <van-popover
                      v-if="parseProtectionLevel(item.protection_level).desc"
                      v-model:show="popoverShow[item.id]"
                      placement="top"
                      trigger="click"
                    >
                      <template #reference>
                        <span class="info-icon" @click.stop="openPopover(item.id)">ⓘ</span>
                      </template>
                      <div class="popover-content">
                        <p>{{ parseProtectionLevel(item.protection_level).desc }}</p>
                      </div>
                    </van-popover>
                  </div>

                  <div class="info-item">
                    <span class="label">地址：</span>
                    <span class="value">{{ item.address || '无地址' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">创建时间：</span>
                    <span class="value">{{ formatDate(item.created_at) }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">最后更新：</span>
                    <span class="value">{{ item.updated_at ? formatDate(item.updated_at) : '未更新' }}</span>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- 右侧操作按钮 -->
          <template #right>
            <div class="action-buttons">
              <van-button
                v-if="userInfo.role === 'admin'"
                square
                type="primary"
                size="large"
                @click="goToEdit(item.id)"
                class="action-btn"
              >
                <van-icon name="edit" /> 编辑
              </van-button>
              <van-button
                v-if="userInfo.role === 'admin'"
                square
                type="danger"
                size="large"
                @click="deleteCategory(item.id)"
                class="action-btn"
              >
                <van-icon name="delete" /> 删除
              </van-button>
              <van-button
                square
                type="success"
                size="large"
                @click="goToMainPage(item.id, item.name)"
                class="action-btn"
              >
                <van-icon name="arrow-right" /> 详情
              </van-button>
            </div>
          </template>
        </van-swipe-cell>

        <!-- 分页组件 -->
        <van-pagination
          v-if="totalPages > 0"
          v-model="currentPage"
          :page-count="totalPages"
          background
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useCategoryPage } from '@/components/composables/useCateGory'
import { useUser } from '@/components/composables/usePersonalInfo'
import { showImagePreview } from 'vant'

// 用户信息
const { userInfo } = useUser()

// 表格逻辑复用
const {
  currentPage,
  pageSize,
  searchKeyword,
  categories,
  total,
  totalPages,
  componentState,
  reloadData,
  handleSearch,
  handleImageError,
  goToCategory,
  goToEdit,
  deleteCategory,
  goToAdd,
  handlePageSizeChange,
  handlePageChange,
  formatDate,
  goToMainPage,
  goHome,
  goToUser,
} = useCategoryPage()

// 预览图片
const previewImage = (src: string) => {
  if (src) {
    showImagePreview([src])
  }
}
// 用于控制每个文物的 popover 是否显示
const popoverShow = ref<Record<number, boolean>>({})

// 打开 popover（点击 ⓘ 时触发）
const openPopover = (id: number) => {
  // 先关闭其他所有 popover
  Object.keys(popoverShow.value).forEach(key => {
    popoverShow.value[Number(key)] = false
  })
  // 打开当前
  popoverShow.value[id] = true
}

// 拆分保护等级字段： "国家级, 由国务院核定..." → { level: "国家级", desc: "由国务院核定..." }
const parseProtectionLevel = (raw: string) => {
  if (!raw || typeof raw !== 'string') {
    return { level: '', desc: '' }
  }
  const parts = raw.split(',').map(part => part.trim()) // 👈 所有部分都 trim
  const level = parts[0]?.trim() || '' // 👈 再次确保 trim
  const desc = parts.slice(1).join(', ')
  return { level, desc }
}

// 保护等级 tag 类型映射
const getTagType = (level: string) => {
  if (!level) return 'info'
  const map: Record<string, string> = {
    国宝单位: 'danger',      // 红色
    省级: 'warning',       // 橙色
    市县级: 'primary',       // 蓝色
    // 未定级: 'success',       // 绿色
  }
  return map[level] || 'default' // 默认灰色
}

// 用于控制每个文物的简介是否展开（默认都收起）
const expandedStates = ref<Record<number, boolean>>({})

// 切换展开状态
const toggleExpand = (id: number) => {
  expandedStates.value[id] = !expandedStates.value[id]
}

</script>

<style scoped>
/* ========== Flex 布局核心 ========== */
.mobile-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-top: 46px; /* 为 fixed 的 navBar 补偿 */
  /* overflow: hidden; */
}

/* 搜索 + 新增区域：固定高度，不伸缩 */
.search-upload-container {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  gap: 2px; /* 控制元素间距 */
}

.search-bar {
  flex: 1;
}

/* 搜索按钮和上传按钮 */
.add-btn {
  height: 32px; /* 与搜索框高度对齐 */
  padding: 0 12px;
  font-size: 14px;
}

/* 可滚动内容区：自动撑满剩余空间 */
.scrollable-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding: 12px 0;
}

/* ========== 其他样式保持不变 ========== */
.state-placeholder {
  padding: 60px 20px;
  text-align: center;
}

.relic-list {
  padding: 0 12px;
}

/* 卡片整体样式 */
.relic-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 16px;
  overflow: hidden;
  transition: transform 0.2s;
}

.relic-card:active {
  transform: scale(0.98);
}

/* 图片区域 */
.image-wrapper {
  height: 160px;
  position: relative;
}

.image-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
  font-size: 14px;
}

/* 内容区域 */
.content-wrapper {
  padding: 14px;
}

.relic-name {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 500;
  color: #2c3e50;
  line-height: 1.4;
}

/* 信息网格 */
.info-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 6px 0;
  font-size: 14px;
  color: #333;
}

.info-item {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.label {
  color: #666;
  font-weight: 500;
  min-width: 80px;
  margin-right: 4px;
}

.value {
  color: #333;
  word-break: break-word;
  flex: 1;
}

/* 简介区域 */
.description-item {
  align-items: flex-start;
}

.value-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
}

.description-text {
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  word-break: break-word;

  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.description-text.expanded {
  -webkit-line-clamp: unset;
  white-space: pre-wrap;
}

.expand-btn {
  align-self: flex-start;
  padding: 2px 8px;
  font-size: 12px;
  height: auto;
}

/* 操作按钮组 */
.action-buttons {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.action-btn {
  height: 100%;
  width: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  padding: 0;
}

/* ⓘ 信息图标 */
.info-icon {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: #1890ff;
  color: white;
  font-size: 12px;
  font-weight: bold;
  margin-left: 6px;
  cursor: pointer;
  user-select: none;
}

/* 弹出层内容样式 */
.popover-content {
  max-width: 280px;
  padding: 12px;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  background-color: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
}

.popover-content p {
  margin: 0;
  word-break: break-word;
}
/* 导航栏左侧“首页”文字样式 */
:deep(.van-nav-bar .nav-text) {
  font-size: 16px;
  color: #1989fa; /* 与 Vant 默认主题色一致 */
  font-weight: 500;
}

/* 可选：添加点击效果 */
:deep(.van-nav-bar .nav-text:hover) {
  opacity: 0.8;
}
/* 面包屑样式 */
.breadcrumb {
  padding: 8px 16px;
  background-color: #f7f8fa;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  /* 确保不被 fixed 的 nav-bar 遮挡 */
  margin-top: 0px; /* van-nav-bar 的默认高度 */
}

.breadcrumb-item {
  color: #1989fa; /* 可点击项用蓝色 */
}

.breadcrumb-item:last-child {
  color: #333;
  font-weight: 500;
}

.breadcrumb-separator {
  margin: 0 1px;
  color: #999;
}
</style>
